# -*-coding: utf-8 -*-
"""
    @Theme   : 
    @Time    : 2024/6/20 9:28
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import json

import click
from faker import Faker

from chatroom import app, r_client


fake = Faker()


@app.cli.command()
@click.option('--drop', is_flag=True, help='Drop Project keys.')
@click.option('--count', default=20, help='Quantity of messages, default is 20.')
def init_redis(drop, count):
    """Drop keys and Generate New Data"""
    client = r_client.client
    if drop:
        cookies = client.keys('cookie-*')
        for cookie in cookies:
            nick = cookie.decode()[7:]
            if msg_keys := client.keys(f'{nick}*'):
                client.delete(*msg_keys)
        if cookies:
            client.delete(*cookies)
        client.delete(r_client.chat_list)
        client.delete(r_client.chat_room_nick_set)
        print('Drop Redis keys OK!')

    for _ in range(count):
        message_info = {
            'msg': fake.sentence(),
            'post_time': fake.date_time_this_month().strftime('%Y-%m-%d %H:%M:%S'),
            'nick': fake.name()
        }
        client.sadd('chat_room_nick_set', message_info['nick'])
        client.rpush('chat_list', json.dumps(message_info))

    print(f'{count} messages have been inserted in chat_list and chat_room_nick_set.')
    print(f'chat_room_nick_set: {client.scard("chat_room_nick_set")} counts.')
    print(f'chat_list: {client.llen("chat_list")} counts.')
